﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Data.SqlClient;
using System.Data.Sql;

namespace PrintServiceMgr
{
    public partial class ConnectStringConfigFrm : Form
    { 
        private const string initConstr = "Server={0};Database={1};Uid={2};Pwd={3}";
        private int _IndexStep = 1;
        #region 加载数据库列表	
        private void loadDbName()
        {
            SqlConnection conn = null;
            try
            {
                string ConStr =string.Empty;
                if (cbCheckType.SelectedIndex==0)
                {
                    ConStr = "Data Source=" + cbServer.Text +";Initial Catalog=master;Integrated Security=True";           
                }
                else
                {
                    ConStr = @"Server=" + cbServer.Text.Trim() +
                             ";Uid=" + tbUid.Text.Trim() +
                             ";pwd=" + tbPwd.Text.Trim() +
                             ";Database=master";
                }
                String SelectDBQuery = "SELECT  NAME  FROM  sysdatabases  ORDER  BY NAME";
                conn = new SqlConnection(ConStr);
                conn.Open();     
                SqlCommand cmd = new SqlCommand(SelectDBQuery, conn);
                SqlDataReader reader = cmd.ExecuteReader();
                cbDbName.Items.Clear();
                while (reader.Read())
                {
                    cbDbName.Items.Add(reader.GetString(0));
                }
                reader.Close();
                cmd.Dispose();
                conn.Close();
            }
            catch (Exception ex)
            {
                cbDbName.Items.Clear();
            }
            finally
            {
                if (conn != null)
                {
                    conn.Close();
                }
            }
        }
        #endregion
        #region 测试数据库连接
        private int testConnectionDB()
        {
            if (cbServer.Text.Trim() == "")
            {
                MessageBox.Show("请选择连接服务器！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return -1;
            }
            if (cbDbName.Text.Trim() == "")
            {
                MessageBox.Show("请选择一个连接数据库！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return -1;
            }
            string conStr = string.Empty;
            if (cbCheckType.SelectedIndex == 0)
            {
                conStr = "Data Source=" + cbServer.Text+";Initial Catalog=master;Integrated Security=True";
            }
            else
            {
                conStr = string.Format(initConstr, cbServer.Text, cbDbName.Text, tbUid.Text, tbPwd.Text);
            }
           
            SqlConnection con = null;
            try
            {
                con = new SqlConnection(conStr);
                con.Open();                
                con.Close();
                return 1;
            }
            catch (Exception ex)
            {
                return 0;
            }
            finally
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();
                }
            }
        }
        #endregion
        #region 加载服务器列表
      
        private int  LoadServers(object sender, DoWorkEventArgs e)
        {
            this.groupBox1.Enabled = false;
            this.btnOk.Enabled = false;
            this.btnCancel.Enabled = false;        
            SqlDataSourceEnumerator instance = SqlDataSourceEnumerator.Instance;
            this.backgroundWorker1.ReportProgress(10);
            System.Data.DataTable table = instance.GetDataSources();
            if (table != null)
            {
                foreach (DataRow dr in table.Rows)
                {
                    cbServer.Items.Add(dr[0].ToString());
                }
            }            
            for (int i = 11; i < progressBar1.Maximum-11; i++)
            {
                if (this.backgroundWorker1.CancellationPending)
                {
                    e.Cancel = true;
                    return -1;
                }
                else
                {
                    this.backgroundWorker1.ReportProgress(i);
                }
                ///   将当前线程挂起指定的时间   
                System.Threading.Thread.Sleep(100);
            }
            if (cbServer.Items.Count < 1)
            {
                cbServer.Items.Add(".");
                cbServer.Items.Add(@".\sqlexpress");
            }
            cbServer.SelectedIndex = 0;
            return -1;              
        }
        #endregion
        private string _DBConnectionStr = string.Empty;
        /// <summary>
        /// 连接字符串
        /// </summary>
        public string DBConnectionStr
        {
            get { return _DBConnectionStr; }
            set { _DBConnectionStr = value; }
        }

        public ConnectStringConfigFrm()
        {
            InitializeComponent();
            backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
            backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
            backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
            try
            {
                backgroundWorker1.RunWorkerAsync();
            }
            catch
            { }            
        }

        void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.progressBar1.Value = e.ProgressPercentage;
        }

        void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            panAlterInfo.Visible = false;
            this.groupBox1.Enabled = true;
            this.btnOk.Enabled = true;
            this.btnCancel.Enabled = true;          
            cbServer.Focus();
        }

        void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            e.Result = (LoadServers(this.backgroundWorker1, e));          
        }      
  
        private void btnOk_Click(object sender, EventArgs e)
        {
            int i = testConnectionDB();
            if (i==-1)
            {
                return;
            }
            if (i==0)
            {
                MessageBox.Show("数据库连接失败，设置参数无效！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            string conStr = string.Empty;
            if (cbCheckType.SelectedIndex == 0)
            {
                conStr = "Data Source=" + cbServer.Text+" ;Initial Catalog="+cbDbName.Text+";Integrated Security=True";
            }
            else
            {
                conStr = string.Format(initConstr, cbServer.Text, cbDbName.Text, tbUid.Text, tbPwd.Text);
            }          
            _DBConnectionStr = conStr;

            this.Close();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
   
        private void btnTest_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            int i = testConnectionDB();
            if (i == -1)
            {
                return;
            }
            else if (i ==1)
            {
                MessageBox.Show("数据库连接成功！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("数据库连接失败！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }   

        private void cbCheckType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbCheckType.SelectedIndex == 0)
            {
                tbPwd.Enabled = false;
                tbUid.Enabled = false;
            }
            else
            {
                tbPwd.Enabled = true;
                tbUid.Enabled = true;
            }
        }

        private void cbDbName_Enter(object sender, EventArgs e)
        {
            loadDbName();
        }

    
    }
}